import bignumber, { type BigNumber } from '@peng_kai/kit/libs/bignumber';

/**
 * 乘精度
 */
export function mulPrecision(value: BigNumber.Value, precision = 6) {
  return bignumber(value).multipliedBy(bignumber(10).pow(precision));
}

/**
 * 除精度
 */
export function divPrecision(value: BigNumber.Value, precision = 6) {
  return bignumber(value).dividedBy(bignumber(10).pow(precision));
}

/**
 * 格式化字符串
 * @param value 数值
 * @returns 字符串
 */
export function formatNumber(
  value: BigNumber.Value,
  decimals = 8,
  round = bignumber.ROUND_DOWN,
  grouping = false,
): string {
  const num = bignumber(value);
  const decimalLen = num.decimalPlaces() ?? 0;
  const showDecimalLen = Math.min(decimalLen, decimals);
  return grouping ? num.toFormat(showDecimalLen, round) : num.toFixed(showDecimalLen, round);
}

/**
 * 将数字缩写
 * @description 1B=10亿，1M=100万，1K=1千
 * @param num
 */
export function numberAbbreviations(num: BigNumber.Value) {
  const _num = bignumber(num);
  if (_num.gte(1000000000))
    return `${_num.dividedBy(1000000000).toFixed(2, bignumber.ROUND_DOWN)}B`;
  else if (_num.gte(1000000))
    return `${_num.dividedBy(1000000).toFixed(2, bignumber.ROUND_DOWN)}M`;
  else if (_num.gte(10000))
    return `${_num.dividedBy(1000).toFixed(1)}K`;
  else
    return _num.toFormat(0, bignumber.ROUND_DOWN);
}
